//
//  ChatInputView.swift
//  Exchange
//
//  Created by rui on 2018/5/8.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit


let kChatBarOriginHeight: CGFloat = 49.0
let kChatBarTextViewMaxHeight: CGFloat = 100
let kChatBarTextViewHeight: CGFloat = kChatBarOriginHeight - 14.0


@objc protocol ChatInputViewDelegate {
    func chatInputViewDidBeginEditing(inputView: ChatInputView)
    func chatInputViewSend(inputView: ChatInputView)
    func chatInputViewUpdateHeight(inputView: ChatInputView,height: CGFloat)
}


class ChatInputView: UIView {
    
    private(set) var inputTextViewCurHeight: CGFloat = kChatBarOriginHeight
    
    private var placeholderLable: UILabel?
    
    weak var delegate: ChatInputViewDelegate?
    
    var placeholder: String? {
        didSet {
            if let placeholderL = placeholderLable {
                placeholderL.text = placeholder
            }else {
                let lbl = UILabel()
                lbl.themeTextColor = ThemeManager.ThemeColorKeys.text3
                lbl.font = UIFont.systemFont(ofSize: 16)
                lbl.textAlignment = .left
                lbl.backgroundColor = UIColor.clear
                placeholderLable = lbl
                lbl.text = placeholder
                self.addSubview(lbl)
            }
        }
    }
    
    private(set) lazy var textView: UITextView = {
        let textView = UITextView()
        textView.themeTextColor = ThemeManager.ThemeColorKeys.text1
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.delegate = self
        textView.returnKeyType = .send
        textView.themeBackground = ThemeManager.ThemeColorKeys.background
        textView.layoutManager.allowsNonContiguousLayout = false;
        textView.addObserver(self, forKeyPath: "attributedText", options: .new, context: nil)
        return textView
    }()
    
    private lazy var sendBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(#imageLiteral(resourceName: "send_chat"), for: .normal)
        btn.addTarget(self, action: #selector(send), for: .touchUpInside)
        return btn
    }()
    
    private var underLine: UIView = {
        let line = UIView()
        line.themeBackground = ThemeManager.ThemeColorKeys.separator
        return line
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initUI()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        sendBtn.width = 32
        sendBtn.height = 32
        sendBtn.right = self.width - 16
        sendBtn.centerY = self.height * 0.5
        textView.height = self.height - 14
        textView.width = sendBtn.x - 16 - 10
        textView.x = 16
        textView.y = 7
        underLine.frame = CGRect(x: 16, y: textView.bottom, width: textView.width, height: 0.5)
        placeholderLable?.frame = CGRect(x: 16, y: 0, width: textView.width, height: underLine.bottom)
    }
    
    func initUI() {
        self.addSubview(textView)
        self.addSubview(sendBtn)
        self.addSubview(underLine)
    }
    
    @objc func send() {
        delegate?.chatInputViewSend(inputView: self)
    }
    
    deinit {
        self.textView.removeObserver(self, forKeyPath: "attributedText")
    }
}

extension ChatInputView: UITextViewDelegate{
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        delegate?.chatInputViewDidBeginEditing(inputView: self)
    }

    func textViewDidChange(_ textView: UITextView) {
        placeholderLable?.isHidden = textView.hasText
        
        var height = textView.sizeThatFits(CGSize(width: textView.width, height: CGFloat.greatestFiniteMagnitude)).height

        height = height > kChatBarTextViewHeight ? height : kChatBarTextViewHeight


        height = height < kChatBarTextViewMaxHeight ? height : textView.height
     
        inputTextViewCurHeight = height + kChatBarOriginHeight - kChatBarTextViewHeight
 
        if inputTextViewCurHeight != textView.height {
            UIView.animate(withDuration: 0.05, animations: {
                self.delegate?.chatInputViewUpdateHeight(inputView: self, height: self.inputTextViewCurHeight)
            })
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            delegate?.chatInputViewSend(inputView: self)
            return false
        }
        return true
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        textView.scrollRangeToVisible(NSMakeRange(textView.text.count, 1))
        self.textViewDidChange(textView)
    }
}
